{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0db192d9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "01a82d478b0e5e941f07c6a8e1f3eff2_4.mp4\n"
     ]
    }
   ],
   "source": [
    "import cv2\n",
    "import os\n",
    "\n",
    "\n",
    "input_path = \"../../assets/video/truck/\"\n",
    "output_path=\"../../assets/image/truck/\"\n",
    "file_names = [f for f in os.listdir(input_path) if f.endswith(\".mp4\")]\n",
    "print(file_names[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "74443022",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提取完成！保存 1278 张图像到 ../../assets/image/truck/\n"
     ]
    }
   ],
   "source": [
    "def extract_frames(video_path, output_dir, format='jpg', frame_interval=1,rescnt=0):\n",
    "    \"\"\"\n",
    "    从视频中提取帧并保存为图像\n",
    "    :param video_path: 视频文件路径\n",
    "    :param output_dir: 输出目录\n",
    "    :param format: 图像格式 ('jpg' 或 'png')\n",
    "    :param frame_interval: 每隔多少帧保存一 (默认为1,即每帧都保存）\n",
    "    \"\"\"\n",
    "    # 确保输出目录存在\n",
    "    os.makedirs(output_dir, exist_ok=True)\n",
    "    \n",
    "    # 打开视频文件\n",
    "    cap = cv2.VideoCapture(video_path)\n",
    "    if not cap.isOpened():\n",
    "        print(\"Error: 无法打开视频文件！\")\n",
    "        return\n",
    "    \n",
    "    frame_count = 0\n",
    "    saved_count = 0\n",
    "    \n",
    "    while True:\n",
    "        ret, frame = cap.read()\n",
    "        if not ret:\n",
    "            break  # 视频结束\n",
    "     \n",
    "        if frame_count % frame_interval == 0:   # 按间隔保存帧\n",
    "            if format.lower() == 'png':\n",
    "                output_path = os.path.join(output_dir, f\"frame_{saved_count+rescnt:05d}.png\")\n",
    "                cv2.imwrite(output_path, frame, [cv2.IMWRITE_PNG_COMPRESSION, 3])  # PNG压缩级别（0-9）\n",
    "            elif format.lower() == 'jpg':\n",
    "                output_path = os.path.join(output_dir, f\"frame_{saved_count+rescnt:05d}.jpg\")\n",
    "                cv2.imwrite(output_path, frame, [cv2.IMWRITE_JPEG_QUALITY, 95])  # JPG质量（0-100）\n",
    "            else:\n",
    "                raise ValueError(\"不支持的格式，请选择 'jpg' 或 'png'\")\n",
    "            saved_count += 1\n",
    "        \n",
    "        frame_count += 1\n",
    "    \n",
    "    cap.release()\n",
    "    return saved_count\n",
    "\n",
    "total=0\n",
    "for file in file_names:\n",
    "    # 使用示例\n",
    "   saved=extract_frames(\n",
    "        video_path=input_path+file,      # 输入视频路径\n",
    "        output_dir=output_path,  # 输出目录\n",
    "        format=\"jpg\",               # 保存为JPG格式\n",
    "        frame_interval=20,           # 每10帧保存1张\n",
    "        rescnt=total\n",
    "    )\n",
    "   assert saved is not None\n",
    "   total+=saved\n",
    "print(f\"提取完成！保存 {total} 张图像到 {output_path}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "yolo",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.23"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
